<template>
  <div class="goods-category">
    <!-- 筛选搜索部分 -->
    <div class="filter-container">
      <el-form :model="filterForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="输入搜索：">
              <el-input v-model="filterForm.name" placeholder="商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品货号：">
              <el-input v-model="filterForm.code" placeholder="商品货号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品分类：">
              <el-cascader
                v-model="filterForm.type_id"
                :options="categoryOptions"
                :props="{ expandTrigger: 'click' }"
                placeholder="请选择分类"
              />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20" align="middle">
          <el-col :span="6">
            <el-form-item label="上架状态：">
              <el-select v-model="filterForm.shelves" placeholder="全部">
                <el-option label="全部" value="all" />
                <el-option label="已上架" value=true />
                <el-option label="已下架" value=false />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核状态：">
              <el-select v-model="filterForm.audit" placeholder="全部">
                <el-option label="全部" value="all" />
                <el-option label="已审核" value="已审核" />
                <el-option label="未审核" value="未审核" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="button-container">
            <el-button type="primary" @click="onSearch">查询结果</el-button>
            <el-button type="primary" @click="onReset">重置</el-button>
            <el-button type="primary" @click="goToAddPage">添加</el-button>
            <el-button
              v-if="!isBatchDeleteMode"
              type="danger"
              @click="startBatchDelete"
            >
              批量删除
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 数据表格部分 -->
    <el-table
    :data="paginatedData"
     border
     style="width: 100%"
     @selection-change="handleSelectionChange"
     :row-key="(row) => row.id"
     >
     <!--添加选择列-->
     <el-table-column
      v-if="isBatchDeleteMode"
      type="selection"
      width="55"
      />
     >
      <el-table-column prop="id" label="编号" width="80" align="center" />
      <el-table-column label="商品图片" width="120" align="center">
        <template #default="scope">
          <img :src="scope.row.image" alt="商品图片" class="product-image" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" min-width="120" />
      <el-table-column prop="remark" label="商品简介" min-width="200" />
      <el-table-column label="价格/货号" width="150">
        <template #default="scope">
          <div>价格：￥{{ scope.row.price }}</div>
          <div>货号：{{ scope.row.code }}</div>
        </template>
      </el-table-column>
      <el-table-column label="标签" width="120" align="center">
        <template #default="scope">
          <div>上架：<el-switch v-model="scope.row.shelves" size="small"  @change="shelvesHandleSwitchChange(scope.row)"/></div>
          <div>新品：<el-switch v-model="scope.row.newProduct" size="small" @change="newProductHandleSwitchChange(scope.row)"/></div>
          <div>推荐：<el-switch v-model="scope.row.recommend" size="small" @change="recommendHandleSwitchChange(scope.row)"/></div>
        </template>
      </el-table-column>
      <el-table-column prop="inventory" label="SKU库存" width="100" align="center" />
      <el-table-column prop="sale" label="销量" width="100" align="center" />
      <el-table-column prop="unit" label="单位" width="80" align="center" />
      <el-table-column prop="audit" label="审核状态" width="100" align="center" />
      <el-table-column label="操作" width="200" align="center">
<!--查看 编辑弹出框-->
        <template #default="scope">
<!--查看-->
          <el-button size="small" type="text" @click="ViewdialogFormVisible1(scope.row)">查看</el-button>
          <el-dialog title="商品查看" :visible.sync="ViewdialogFormVisible" :modal="false">
            <el-form :model="viewForm" :disabled="true">
              <el-form-item label="编号" :label-width="formLabelWidth">
                <el-input v-model=viewForm.id></el-input>
              </el-form-item>
              <el-form-item label="商品名称" :label-width="formLabelWidth">
                <el-input v-model=viewForm.name ></el-input>
              </el-form-item>
              <el-form-item label="商品简介" :label-width="formLabelWidth">
                <el-input v-model=viewForm.remark ></el-input>
              </el-form-item>
              <el-form-item label="价格" :label-width="formLabelWidth">
                <el-input v-model=viewForm.price ></el-input>
              </el-form-item>
              <el-form-item label="货号" :label-width="formLabelWidth">
                <el-input v-model=viewForm.inventory ></el-input>
              </el-form-item>
              <el-form-item label="销量" :label-width="formLabelWidth">
                <el-input v-model=viewForm.sale ></el-input>
              </el-form-item>
              <el-form-item label="单位" :label-width="formLabelWidth">
                <el-input v-model=viewForm.unit ></el-input>
              </el-form-item>
              <el-form-item label="审核状态" :label-width="formLabelWidth">
                <el-input v-model=viewForm.audit ></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="ViewdialogFormVisible = false">返 回</el-button>
            </div>
          </el-dialog>
<!--编辑-->
          <el-button size="small" type="text" @click="EditdialogFormVisible1(scope.row)">编辑</el-button>
          <el-dialog title="商品编辑" :visible.sync="EditdialogFormVisible" :modal="false">
            <el-form :model="EditForm">
<!--              <el-form-item label="编号" :label-width="formLabelWidth" >-->
<!--                <el-input v-model=EditForm.id></el-input>-->
<!--              </el-form-item>-->

              <el-form-item label="商品名称" :label-width="formLabelWidth">
                <el-input v-model=EditForm.name ></el-input>
              </el-form-item>
              <el-form-item label="商品简介" :label-width="formLabelWidth">
                <el-input v-model=EditForm.remark ></el-input>
              </el-form-item>
              <el-form-item label="价格" :label-width="formLabelWidth">
                <el-input v-model=EditForm.price ></el-input>
              </el-form-item>
              <el-form-item label="货号" :label-width="formLabelWidth">
                <el-input v-model=EditForm.inventory ></el-input>
              </el-form-item>
              <el-form-item label="销量" :label-width="formLabelWidth">
                <el-input v-model=EditForm.sale ></el-input>
              </el-form-item>
              <el-form-item label="单位" :label-width="formLabelWidth">
                <el-input v-model=EditForm.unit ></el-input>
              </el-form-item>
              <el-form-item label="审核状态" :label-width="formLabelWidth">
                <el-input v-model=EditForm.audit ></el-input>
              </el-form-item>

              <!--类型选择-->
              <el-form-item label="类型变更" :label-width="formLabelWidth">
                <div class="chooseGoodType" >
                  <el-select v-model="EditForm.type_id" placeholder="若要更改商品类型就请选择"  @click.native="getEditForm">
                    <!--  EditForm.type_id 也就相当于value
                          value: '选项1',
                          label: '黄金糕'
                          上面这是给的数据的示例
                          你的value就是后端type表的id
                          意思就是你的这个商品对应哪一个小类
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"-->

<!--                    是下面里面的-->
<!--                    @change="editHandleChange"-->
                    <el-option

                        v-for="item in editGoodsId"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="EditdialogFormVisibleSubmit">确 定</el-button>
              <el-button  @click="EditdialogFormVisible = false">取 消</el-button>
            </div>
          </el-dialog>
<!--删除-->
          <el-button size="small" type="danger" @click="SingleDeletion">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加批量删除操作栏 -->
    <div v-if="isBatchDeleteMode" class="batch-delete-bar">
      <el-button type="primary" @click="confirmBatchDelete">确认删除</el-button>
      <el-button @click="cancelBatchDelete">取消</el-button>
      <span class="selected-count">已选择 {{ selectedRows.length }} 项</span>
    </div>



    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      />
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { mapState } from 'vuex'
// import $axios from "core-js/internals/queue";
export default {
  data() {
    return {
      loading: false,
      categoryOptions: [],
      // 筛选表单数据
      filterForm: {
        name: "",
        code: "",
        type_id: "",
        shelves: "",
        audit: "",
      },
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      isBatchDeleteMode: false,
      selectedRows: [],
      // 查看弹出表单
      ViewdialogFormVisible: false,
      viewForm: {
        id:'',
        name: '',
        remark: '',
        price: '',
        code: '',
        shelves: '',
        newProduct: '',
        recommend: '',
        inventory: '',
        type_id: '',
        audit: '',
        sale:'',
        unit: '',
        super_type: ''
      },
      formLabelWidth: '120px',

    // 编辑弹出表单
      EditdialogFormVisible: false,
      EditForm: {
        id:'',
        name: '',
        remark: '',
        price: '',
        code: '',
        shelves: '',
        newProduct: '',
        recommend: '',
        inventory: '',
        type_id: 0,
        audit: '',
        sale:'',
        unit: '',
        super_type: ''
      },
      // 同年
      editGoodsId:[],
      typeOptions:'',
      editGoodsShow:[],
      // 这个就是转换id到typename
      edittypeName:'',
      initialEditGoodsId:0
    };
  },
  computed: {
    ...mapState('goods',['Goods']),
    // 计算当前页的数据
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end);
    },
    totalCount() {
      return this.tableData.length;
    }
  },
  mounted() {
    this.fetchCategoryOptions();
    this.$axios.get('http://localhost:8080/Goods/selectAll').then((res) => {//axios发送post请求，后台验证
      this.tableData=res.data.data.Goods
      this.$store.dispatch("goods/SET_DATA", res.data.data)
    })
  },
  beforeUnmount() {
    const container = this.$el.querySelector('.goods-category');
    container.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    onSearch() {
      if(this.filterForm.type_id[1]!=null){
    this.filterForm.type_id=String(this.filterForm.type_id[1])
      }1
      console.log(this.filterForm)

      axios.post("http://localhost:8080/Goods/ConditionalQuery",this.filterForm).then((res)=>{
        this.tableData=res.data.data.Goods
      })
    },
    onReset() {
      this.$axios.get('http://localhost:8080/Goods/selectAll').then((res) => {
      this.tableData=res.data.data.Goods
      this.$store.dispatch("goods/SET_DATA", res.data.data)
    })
    },
    goToAddPage() {
      this.$router.push({ path: "/home/addProduct" }); // 跳转到添加商品页面
    },

    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
    },
    handleCurrentChange(page) {
      this.currentPage = page;
    },
    startBatchDelete() {
      this.isBatchDeleteMode = true;
      this.selectedRows = [];
    },
    cancelBatchDelete() {
      this.isBatchDeleteMode = false;
      this.selectedRows = [];
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    confirmBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要删除的项目');
        return;
      }

      this.$confirm('确定要删除选中的项目吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        const ids = this.selectedRows.map(row => row.id);
        this.handleDelete(ids)
        this.$message({
          type: 'success',
          message: `成功删除 ${ids.length} 项`
        });

        this.selectedRows = [];
        this.isBatchDeleteMode = false;
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    SingleDeletion(){
      const targetRow = event.target.closest('tr');
      let ids=[]
      ids.push(parseInt(targetRow.children[0].children[0].textContent))
      this.$confirm('确定要删除选中的项目吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.handleDelete(ids)
        this.$message({
          type: 'success',
          message: `成功删除 ${ids.length} 项`
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleScroll(e) {
      const filterContainer = this.$el.querySelector('.filter-container');
      if (e.target.scrollTop > 0) {
        filterContainer.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.1)';
      } else {
        filterContainer.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.05)';
      }
    },
    async fetchCategoryOptions() {
      this.loading = true;  // 开始加载
      try {
        const response = await this.$axios.post('http://localhost:8080/Goods/selectGoodsTypeList');
        if (response.data.code === 20000) {  // 注意这里改成 20000
          // 处理返回的数据结构
          this.categoryOptions = response.data.data.goodsTypeList.map(item => ({
            value: item.id,
            label: item.typeName,
            children: item.children.map(child => ({
              value: child.id,
              label: child.typeName
            }))
          }));
        } else {
          this.$message.error('获取商品分类失败：' + response.data.message);
        }
      } catch (error) {
        console.error('获取商品分类出错：', error);
        this.$message.error('获取商品分类失败，请检查网络连接');
      } finally {
        this.loading = false;  // 结束加载
      }
    },
    handleDelete(ids){
      this.$axios.post('http://localhost:8080/Goods/delete',ids).then((res) => {
        this.tableData=res.data.data.Goods
        this.$store.dispatch("goods/SET_DATA", res.data.data)
      })
    }
    ,
    shelvesHandleSwitchChange(row){
      const id =row.id
      console.log(id)
      axios.post("http://localhost:8080/Goods/changeShelves", { id: row.id }
      )
          .then(response => {
                if (response.data.code === 20000){
                  console.log("更改成功")
                }
                else console.log(response.data.message)
              }
             )
    },
    newProductHandleSwitchChange(row){
      const id =row.id
      console.log(id)
      axios.post("http://localhost:8080/Goods/changeNewProduct",{ id: row.id })
          .then(response => {
                if (response.data.code === 20000){
                  console.log("更改成功")
                }
                else console.log(response.data.message)
              }
          )
    },
    recommendHandleSwitchChange(row){
      const id =row.id
      console.log(id)
      axios.post("http://localhost:8080/Goods/changeRecommend",{ id: row.id })
          .then(response => {
                if (response.data.code === 20000){
                  console.log("更改成功")
                }
                else console.log(response.data.message)
              }
          )
    },
    ViewdialogFormVisible1(row){
      this.ViewdialogFormVisible=true
      this.viewForm ={
        id:row.id,
        name: row.name,
        remark: row.remark,
        price: row.price,
        code: row.code,
        shelves: row.shelves,
        newProduct: row.newProduct,
        recommend: row.recommend,
        inventory: row.inventory,
        type_id: row.type_id,
        audit: row.audit,
        sale: row.sale,
        unit: row.sale,
        super_type: row.super_type
      }
    },
    EditdialogFormVisible1(row){
      this.EditdialogFormVisible=true
      // 初始 初始id
      this.initialEditGoodsId =row.id
          // console.log(row.remark)
      // console.log("下面这个是row")
      // console.log(row)

      // 先要拿到editGoodsId呀 不过现在点那个选择器 也会执行一次这个方法后面优化好了
      this.getEditForm()
      // 这里执行把typeid拿出来然后转化成typename
      // EditFormIdToType方法返回对应的 typeName 或空字符串
      const typeName = this.EditFormIdToType(this.EditForm.type_id,this.editGoodsId);
      this.edittypeName = typeName
      this.EditForm ={
        id:row.id,
        name: row.name,
        remark: row.remark,
        price: row.price,
        code: row.code,
        shelves: row.shelves,
        newProduct: row.newProduct,
        recommend: row.recommend,
        inventory: row.inventory,
        type_id: row.type_id,
        audit: row.audit,
        sale: row.sale,
        unit: row.sale,
        super_type: row.super_type
      }
    },
    getEditForm(){
      // console.log("执行getEditForm方法去拿所有二级分类的name了")
      axios.get("http://localhost:8080/Goods/getSecondTypeGoodsList")
          .then(res =>
          {
            const rawData = res.data.data.secondTypeGoodsList;
            console.log("转换前的数据:", rawData);
            // 转换数据格式
            this.editGoodsId = rawData.map(item => ({
              key: item.id,
              value: item.id,
              label: item.typeName
            }));
            console.log("转换后的数据:", this.editGoodsId);
          })


    }
    ,
    EditdialogFormVisibleSubmit(){
      console.log("确认后提交的")
      const submitEditform = this.EditForm
      console.log(this.EditForm)
      if (submitEditform.type_id === null || submitEditform.type_id === undefined){
        submitEditform.type_id = this.initialEditGoodsId
        console.log("这是 没用更改类型 马上要给后端的数据")
        console.log(submitEditform)
        axios.post("http://localhost:8080/Goods/updateGood",submitEditform).then((res) =>{
        this.tableData = res.data.Goods
          // console.log("这是后端返回来的数据")
          // console.log( this.tableData)
          window.location.reload(); // 强制刷新页面
                })
      }
      else {
        console.log("这是 更改类型后 马上要给后端的数据")
        console.log(submitEditform)
        axios.post("http://localhost:8080/Goods/updateGood",submitEditform).then((res) =>{
          this.tableData = res.data.Goods
          // console.log("这是后端返回来的数据")
          // console.log( this.tableData)
          window.location.reload(); // 强制刷新页面
        })
      }

      //关闭编辑弹窗
      this.EditdialogFormVisible = false


    },
    EditFormIdToType(type_id, editGoodsId) {
      const selectedItem = editGoodsId.find(item => item.value === type_id);
      return selectedItem ? selectedItem.label : ""; // 返回对应的 typeName 或空字符串
    }
  },

}
</script>

<style scoped>
.goods-category {
  height: calc(100vh - 84px);
  overflow-y: auto;
  position: relative;
  background: #f5f7fa;
}

.filter-container {
  padding: 20px;
  background: #fff;
  border-bottom: 1px solid #ebeef5;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.button-container {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  align-items: center;
}

.batch-delete-bar {
  margin: 10px 0;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.selected-count {
  margin-left: 10px;
  color: #606266;
}

.button-container {
  border-radius: 4px;
  display: flex;
  gap: 10px;
  /* 按钮之间的间距 */
  justify-content: flex-end;
  /* 左对齐 */
  align-items: center;
  gap: 10px;
}

:deep(.el-table) {
  --el-table-row-height: 50px;
}

:deep(.el-table__row) {
  height: var(--el-table-row-height);
}

:deep(.el-table td) {
  padding: 5px 0;
}

.product-image {
  width: 40px;
  height: 40px;
  object-fit: cover;
}

.switch-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 2px 0;
  padding: 0 4px;
}

.switch-label {
  font-size: 12px;
  color: #606266;
  margin-right: 4px;
}

:deep(.el-switch) {
  margin: 0;
  transform: scale(0.9);
}

:deep(.el-button--text) {
  margin: 0 2px;
  padding: 4px 8px;
}

.pagination-container {
  margin: 15px 20px;
  padding: 15px;
  display: flex;
  justify-content: flex-end;
  background: #fff;
  border-radius: 4px;
  position: sticky;
  bottom: 0;
  z-index: 10;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.05);
}

/* 自定义滚动条样式 */
.goods-category::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.goods-category::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.goods-category::-webkit-scrollbar-track {
  background: #f5f7fa;
}

/* 优化操作列按钮的样式 */
:deep(.el-button--text) {
  padding: 2px 4px;
  margin: 0 2px;
}

/* 确保表格填满容器 */
:deep(.el-table) {
  width: 100% !important;
  margin-bottom: 20px;
}

/* 调整表格内容的换行 */
:deep(.el-table .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chooseGoodType{
  position: relative;
  right: 300px;
}
   /* ... 已有的样式 ... */
 .modal-mask {
   position: fixed;
   z-index: 9;
   left: 0;
   top: 0;
   width: 100%;
   height: 100%;
   background-color: rgba(0, 0, 0, 0.5);
 }
</style>
